﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Xenta.Enums;
using Xenta.Utils;

namespace Xenta.Collections
{
    /// <summary>
    /// Represents the search result.
    /// </summary>
    /// <typeparam name="TItem">The type of items in the result.</typeparam>
    public class SearchResult<TItem> : IEnumerable<TItem>, 
        IDisclosable
    {
        #region Properties

        /// <summary>
        /// Gets or sets the total number of items available.
        /// </summary>
        public long TotalCount
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the sequence of items.
        /// </summary>
        public IEnumerable<TItem> Items
        {
            get;
            set;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Discloses the search result.
        /// </summary>
        /// <param name="level">The disclosure level.</param>
        /// <param name="options">The disclosure options.</param>
        /// <returns>The search result object.</returns>
        public virtual object Disclose(DisclosureLevel level, IDictionary<String, String> options)
        {
            var obj = new Dictionary<String, Object>
            {
                {"TotalCount", TotalCount},
                {"Items", Enumerable.Empty<Object>()}
            };
            if(Items.Any())
            {
                if(typeof(IDisclosable).IsAssignableFrom(typeof(TItem)))
                    obj["Items"] = Items.Cast<IDisclosable>().Map(x => x.Disclose(level, options));
                else
                    obj["Items"] = Items;
            }
            return obj;
        }

        /// <summary>
        /// Returns an enumerator that iterates through the collection.
        /// </summary>
        /// <returns>
        /// An enumerator that can be used to iterate through the collection.
        /// </returns>
        public IEnumerator<TItem> GetEnumerator()
        {
            return Items.GetEnumerator();
        }

        /// <summary>
        /// Returns an enumerator that iterates through a collection.
        /// </summary>
        /// <returns>
        /// An enumerator that can be used to iterate through the collection.
        /// </returns>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion
    }
}
